import React, { useState, useEffect } from 'react';
import { View, Text, StyleSheet, ScrollView, Alert, ActivityIndicator } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation } from '@react-navigation/native';
import { Ionicons } from '@expo/vector-icons';
import UploadField from '../components/UploadField';
import AppHeader from '../components/AppHeader';
import GradientButton from '../components/GradientButton';
import InputField from '../components/InputField';
import { Colors } from '../constants/colors';
import { profileService } from '../services';
import { UserProfileVo } from '../types/api';

export default function ProfileEditScreen() {
  const navigation = useNavigation();
  const [profile, setProfile] = useState<UserProfileVo | null>(null);
  const [avatar, setAvatar] = useState('');
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  // 加載用戶資料
  const loadProfile = async () => {
    try {
      setLoading(true);
      const profileData = await profileService.getProfile();
      setProfile(profileData);
      setAvatar(profileData.avatar || '');
    } catch (error: any) {
      console.error('加載用戶資料失敗:', error);
      Alert.alert('錯誤', '加載用戶資料失敗');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadProfile();
  }, []);



  const handleSave = async () => {
    setSaving(true);
    try {
      await profileService.updateProfile({
        avatar: avatar,
      });

      Alert.alert('成功', '頭像更新成功', [
        { text: '確定', onPress: () => navigation.goBack() }
      ]);
    } catch (error: any) {
      console.error('更新頭像失敗:', error);
      Alert.alert('錯誤', error.message || '更新頭像失敗');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <SafeAreaView style={styles.container}>
        <AppHeader title="個人資料" showBack />
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={Colors.primary} />
          <Text style={styles.loadingText}>加載中...</Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      <AppHeader title="個人資料" showBack />
      
      <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
        <View style={styles.form}>
          {/* Profile Picture Section - card style */}
          <View style={{ marginBottom: 12 }}>
            <UploadField
              label="頭像"
              tipText="更換頭像"
              uri={avatar}
              onUploadComplete={(ossUrl) => setAvatar(ossUrl)}
            />
          </View>

          <GradientButton
            title={saving ? "保存中..." : "確定"}
            onPress={handleSave}
            disabled={saving}
            style={styles.saveButton}
          />
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: Colors.white,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    marginTop: 16,
    fontSize: 16,
    color: Colors.gray[600],
  },
  content: {
    flex: 1,
  },
  form: {
    padding: 24,
  },
  profileSection: {
    marginBottom: 32,
  },
  label: {
    fontSize: 16,
    fontWeight: '600',
    color: Colors.gray[700],
    marginBottom: 16,
  },
  avatarContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  avatar: {
    width: 64,
    height: 64,
    borderRadius: 32,
  },
  changeAvatarButton: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: Colors.primary,
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 8,
  },
  changeAvatarText: {
    color: Colors.white,
    fontSize: 14,
    fontWeight: '500',
    marginLeft: 8,
  },
  formGroup: {
    marginBottom: 24,
  },
  inputContainer: {
    position: 'relative',
  },
  input: {
    borderWidth: 1,
    borderColor: Colors.gray[300],
    borderRadius: 12,
    paddingHorizontal: 16,
    paddingVertical: 12,
    paddingRight: 48,
    fontSize: 16,
    backgroundColor: Colors.white,
    minHeight: 48, // 确保安卓上有足够的高度
    textAlignVertical: 'center', // 安卓文本垂直居中
  },
  inputIcon: {
    position: 'absolute',
    right: 16,
    top: 16,
  },
  saveButton: {
    marginTop: 32,
  },
});